package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.commons.LogOperation;
import com.itheima.exception.CannotDeleteException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @LogOperation
    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);

    }

    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }

    @Override
    public Clazz selectById(Integer id) {
        return clazzMapper.selectById(id);
    }

    @LogOperation
    @Override
    public void deleteById(Integer id) {
        int count = studentMapper.countByClazzId(id);
        if (count>0){
            throw new CannotDeleteException("对不起，当前班级下有学生，不能直接删除！");
        }
        clazzMapper.deleteById(id);
    }

    @LogOperation
    @Override
    public void put(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.put(clazz);
    }


    @Override
    public PageResult<Clazz> page(ClazzQueryParam param) {
        LocalDate now = LocalDate.now();
        PageHelper.startPage(param.getPage(),param.getPageSize());
        List<Clazz> clazzList = clazzMapper.page(param);
        Page<Clazz> p = (Page<Clazz>) clazzList;
        List<Clazz> list = p.getResult();
        for (Clazz clazz : list) {
            if (clazz.getBeginDate()!=null && clazz.getEndDate()!=null){
                if (clazz.getBeginDate().isAfter(now)){
                    clazz.setStatus("未开班");
                }else if (clazz.getEndDate().isBefore(now)){
                    clazz.setStatus("已结课");
                }else {
                    clazz.setStatus("开班中");
                }
            }else {
                clazz.setStatus("未知");
            }
        }
        return new PageResult<Clazz>(p.getTotal(),list);
    }
}
